from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
import json

User = get_user_model()


class AgentType(models.Model):
    """智能体类型"""
    name = models.CharField(max_length=100, unique=True, verbose_name="类型名称")
    description = models.TextField(verbose_name="类型描述")
    icon = models.CharField(max_length=50, default='robot', verbose_name="图标")
    capabilities = models.JSONField(default=list, verbose_name="能力列表")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "智能体类型"
        verbose_name_plural = "智能体类型"
        db_table = 'agents_type'
    
    def __str__(self):
        return self.name


class Agent(models.Model):
    """智能体模型"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('active', '活跃'),
        ('training', '训练中'),
        ('inactive', '停用'),
        ('error', '错误')
    ]
    
    name = models.CharField(max_length=100, verbose_name="智能体名称")
    description = models.TextField(verbose_name="描述")
    avatar = models.CharField(max_length=500, blank=True, null=True, verbose_name="头像")
    
    # 关联
    creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_agents', verbose_name="创建者")
    agent_type = models.ForeignKey(AgentType, on_delete=models.CASCADE, verbose_name="智能体类型")
    
    # 配置
    system_prompt = models.TextField(verbose_name="系统提示词")
    personality = models.JSONField(default=dict, verbose_name="个性设置")
    capabilities = models.JSONField(default=list, verbose_name="能力配置")
    knowledge_domains = models.JSONField(default=list, verbose_name="知识领域")
    
    # AI模型配置
    model_name = models.CharField(max_length=100, default='gpt-3.5-turbo', verbose_name="AI模型")
    temperature = models.FloatField(default=0.7, verbose_name="创造性参数")
    max_tokens = models.PositiveIntegerField(default=2048, verbose_name="最大令牌数")
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name="状态")
    is_public = models.BooleanField(default=False, verbose_name="公开")
    is_featured = models.BooleanField(default=False, verbose_name="推荐")
    
    # 统计
    usage_count = models.PositiveIntegerField(default=0, verbose_name="使用次数")
    rating = models.FloatField(default=0.0, verbose_name="评分")
    rating_count = models.PositiveIntegerField(default=0, verbose_name="评分次数")
    
    # 时间戳
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    last_used_at = models.DateTimeField(blank=True, null=True, verbose_name="最后使用时间")

    class Meta:
        verbose_name = "智能体"
        verbose_name_plural = "智能体"
        db_table = 'agents_agent'
        ordering = ['-created_at']

    def __str__(self):
        return self.name
    
    def update_usage(self):
        """更新使用统计"""
        self.usage_count += 1
        self.last_used_at = timezone.now()
        self.save(update_fields=['usage_count', 'last_used_at'])


class AgentRating(models.Model):
    """智能体评分"""
    agent = models.ForeignKey(Agent, on_delete=models.CASCADE, related_name='ratings')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.PositiveIntegerField(choices=[(i, str(i)) for i in range(1, 6)], verbose_name="评分")
    comment = models.TextField(blank=True, verbose_name="评论")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "智能体评分"
        verbose_name_plural = "智能体评分"
        db_table = 'agents_rating'
        unique_together = ['agent', 'user']
    
    def __str__(self):
        return f"{self.user.username} - {self.agent.name}: {self.rating}星"


class Conversation(models.Model):
    """对话记录"""
    agent = models.ForeignKey(Agent, on_delete=models.CASCADE, related_name='conversations')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='conversations')
    title = models.CharField(max_length=200, verbose_name="对话标题")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "对话"
        verbose_name_plural = "对话"
        db_table = 'agents_conversation'
        ordering = ['-updated_at']
    
    def __str__(self):
        return f"{self.user.username} - {self.agent.name}: {self.title}"


class Message(models.Model):
    """消息记录"""
    ROLE_CHOICES = [
        ('user', '用户'),
        ('assistant', '助手'),
        ('system', '系统')
    ]
    
    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages')
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, verbose_name="角色")
    content = models.TextField(verbose_name="消息内容")
    metadata = models.JSONField(default=dict, verbose_name="元数据")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "消息"
        verbose_name_plural = "消息"
        db_table = 'agents_message'
        ordering = ['created_at']
    
    def __str__(self):
        return f"{self.role}: {self.content[:50]}..."